%
% if the 'aafRawData' matrix has 2 columns then the first one is the event type,
% the second one is the timestamp in milliseconds. It is a circular buffer,
% and to find where the last sample has been inserted one has just to look
% for the 'max' in the column of the time. This case happens when the method is
% fed by Labview.
%
% if the 'aafRawData' matrix has 7 columns then the columns 2, 3 and 4 are the ones
% we are interested into. This case happens when the method postprocesses data
% coming from the website
%
function aafData = SortData( aafRawData, iStartingTime )
	%
	global bPrintDebugInformation;
	global tFileID;
	%
	% DEBUG
	if( bPrintDebugInformation )
		%
		fprintf(tFileID, 'Sorting the raw data\n');
		%
	end;%
	% 
	switch( size( aafRawData, 2 ) )
		%
		case 2
			aafData = [ aafRawData, zeros( size(aafRawData(:, 1)) ) ];
		%
		case 7
			aafData = [ aafRawData(:, 2:3), Time.IntegerToJulianDate( aafRawData(:, 4) ) ];
		%
		otherwise
			error('inconsistent number of columns for the raw data');
		%
	end;% switch on number of columns of raw data
	%
	%
	% for readability
	TIME_COLUMN = 2;
	%
	% trick to have faster computations: if the starting time is bigger
	% than the maximum of the times saw in the raw events, then return
	% immediately
	if( iStartingTime > max( aafData(:, TIME_COLUMN) ) )
		%
		if( bPrintDebugInformation )
			%
			fprintf(tFileID, 'there is nothing new to be processed => exit immediately\n');
			%
		end;%
		%
		aafData = [];
		return;
		%
	end;%
	%
	% if we find that the time is decreasing somewhere then do the sorting
	if( sum( diff(aafData( :, TIME_COLUMN )) < 0 ) )
		%
		% find the sorting indexes
		[ ~, aiSortingIndexes ] = sort( aafData( :, TIME_COLUMN ), 'ascend' );
		%
		% sort the matrix
		aafData = [ aafData( aiSortingIndexes, 1 ), aafData( aiSortingIndexes, 2 ), aafData( aiSortingIndexes, 3 ) ];
		%
		if( bPrintDebugInformation )
			%
			fprintf(tFileID, 'Sorting actually performed => there were some data that were unsorted\n');
			%
		end;%
		%
	else%
		%
		if( bPrintDebugInformation )
			%
			fprintf(tFileID, 'Sorting actually not performed => all the data were already sorted\n');
			%
		end;%
		%
	end;%
	%
	% DEBUG
	if( bPrintDebugInformation )
		%
		fprintf(tFileID, 'Ended sorting the old data\n');
		%
	end;%
	%	
end % function

